<template>
  <div>
    <van-nav-bar :title="nickname"></van-nav-bar>
    <div :class="v.direction === 1 ? 'right' : 'left'" v-for="(v, i) in renderChatList" :key="i">
      <van-image
        round
        width="40px"
        height="40px"
        :src="v.direction === 1 ? v.doctorHeadPic : v.userHeadPic"
        error-icon="https://img95.699pic.com/xsj/0p/ew/kg.jpg%21/fh/300"
      />
      <div>{{ v.content }}</div>
    </div>
    <input
      @keyup.enter="enter"
      v-model="value"
      style="position: fixed; bottom: 0; width: 100%; height: 40px; border: 1px solid #ccc"
    />
  </div>
</template>

<script lang="ts" setup>
import { request } from '../../utils/request'
import { useRoute } from 'vue-router'
import { computed, onMounted, onUnmounted, ref } from 'vue'

interface ChatItem {
  askTime: number
  content: string
  direction: number
  doctorHeadPic: string
  msgType: number
  userHeadPic: string
}
const value = ref('')
const route = useRoute()
// 查询参数
const nickname = route.query.nickname as string
const userId = route.query.userId

// 获取动态路由参数
const dynamicId = route.params.id

// 回撤
const enter = () => {
  // 发送数据
  const params = {
    inquiryId: dynamicId,
    content: value.value,
    type: 1,
    userId: userId
  }
  request({
    method: 'post',
    url: '/health/doctor/inquiry/verify/v1/pushMessage',
    params: params
  }).then((resp) => {
    detailList()
    ws.send('消息来了')
  })
}
// 聊天列表
const chatList = ref<ChatItem[]>([])
const renderChatList = computed(() => {
  return [...chatList.value].reverse()
})
// 获取聊天列表
const detailList = async () => {
  const res = await request({
    url: '/health/doctor/inquiry/verify/v1/findInquiryDetailsList',
    params: {
      recordId: dynamicId,
      page: 1,
      count: 20
    }
  })
  // console.log(res.data.result)
  chatList.value = res.data.result
}
detailList()

const ws = new WebSocket('ws://localhost:8080')

ws.onopen = () => {
  console.log('医生端和服务器建立了WebSocket链接')
}

ws.onmessage = () => {
  console.log('医生端服务器消息来了')
  detailList()
}
// const timer = ref()
// onMounted(() => {
//   timer.value = setInterval(() => {
//     detailList()
//   }, 1000)
// })

// onUnmounted(() => {
//   clearInterval(timer.value)
// })
</script>

<style scoped lang="scss">
.left {
  display: flex;
  flex-direction: row;
  img {
    width: 50px;
    height: 50px;
  }
}
.right {
  display: flex;
  flex-direction: row-reverse;
  img {
    width: 50px;
    height: 50px;
  }
}
</style>
